//
//  IGCaptchaView.m
//  jingdongfang
//
//  Created by BOE on 2018/4/3.
//  Copyright © 2018年 BOE-SBG-CTO. All rights reserved.
//

#import "IGCaptchaView.h"
#import "KLCPopup.h"
#import "IGCaptchApi.h"

@interface IGCaptchaView()<UITextFieldDelegate>
@property (nonatomic, strong) UIButton *sureButton;
@property (nonatomic, strong) UITextField *capTextField;

@property (nonatomic, strong) UIImageView *captchaView;
@property (nonatomic, copy) CaptchaBlock captchaBlock;

@property (nonatomic, copy) NSString *num;
@end

@implementation IGCaptchaView

+ (IGCaptchaView *)num:(NSString *)phone showCaptcha:(CaptchaBlock)captchaBlock {
    IGCaptchaView *captchaView = [[IGCaptchaView alloc] initWithFrame:CGRectMake(0, 0, 300, 250)];
    captchaView.backgroundColor = [UIColor whiteColor];
    captchaView.layer.masksToBounds = YES;
    captchaView.layer.cornerRadius = 5;
    captchaView.layer.borderColor = [UIColor lightGrayColor].CGColor;
    captchaView.layer.borderWidth = 1.0;
    captchaView.captchaBlock = captchaBlock;
    captchaView.num=phone;
    [captchaView show];
    [captchaView requestCap];
    
    UIButton *closeBtn = [[UIButton alloc] initWithFrame:CGRectMake(300-40, 0, 40, 40)];
    [captchaView addSubview:closeBtn];
    [closeBtn setTapActionWithBlock:^{
        [KLCPopup dismissAllPopups];
    }];
    [closeBtn setImage:[UIImage imageNamed:@"pub_close"] forState:UIControlStateNormal];
    return captchaView;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self createUI];
        __weak typeof(self) weakSelf = self;
        [self setTapActionWithBlock:^{
            [weakSelf.capTextField endEditing:YES];
        }];
    }
    return self;
}

- (void)requestCap {
    __weak typeof(self) weakSelf = self;
    IGCaptchApi *captchApi = [IGCaptchApi new];
    captchApi.phone=weakSelf.num;
    [captchApi startWithDecodeClass:[IGCaptchResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject) {
            IGCaptchResp *resp = responseObject;
            NSString *dataStr = resp.data.code;
            
            NSData *data = [[NSData alloc]initWithBase64EncodedString:dataStr options:NSDataBase64DecodingIgnoreUnknownCharacters];
            UIImage *image = [UIImage imageWithData:data];
            dispatch_async(dispatch_get_main_queue(), ^{
                weakSelf.captchaView.image = image;
            });
        }
    }];
}

- (void)createUI {
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.text = NSLocalizedString(@"Identifying Code", nil);
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.font = [UIFont boldSystemFontOfSize:18.0];
    titleLabel.textColor = [UIColor c4Color];
    [self addSubview:titleLabel];
    
    [self addSubview:self.capTextField];
    [self addSubview:self.captchaView];
    [self addSubview:self.sureButton];
    
    UILabel *changeLabel = [[UILabel alloc] init];
    changeLabel.text = NSLocalizedString(@"Refresh", nil);
     UITapGestureRecognizer *labelTapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labelClick)];
    changeLabel.textAlignment = NSTextAlignmentCenter;
    changeLabel.font = [UIFont font12];
    changeLabel.textColor = [UIColor c1Color];
    [changeLabel addGestureRecognizer:labelTapGestureRecognizer];
    changeLabel.userInteractionEnabled = YES;
    [self addSubview:changeLabel];
    
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(25);
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(40);
    }];
    [self.capTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(titleLabel.mas_bottom).mas_offset(30);
        make.left.mas_equalTo(20);
        make.width.mas_equalTo(135);
        make.height.mas_equalTo(40);
    }];
    
    [self.captchaView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(40);
        make.width.mas_equalTo(110);
        make.top.mas_equalTo(self.capTextField.mas_top);
        make.right.mas_equalTo(-20);
    }];
    
    [changeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(110);
        make.height.mas_equalTo(30);
        make.top.mas_equalTo(self.captchaView.mas_bottom).mas_offset(5);
        make.right.mas_equalTo(self.captchaView.mas_right);
    }];
    [self.sureButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(40);
        make.width.mas_equalTo(240);
        make.top.mas_equalTo(self.capTextField.mas_bottom).mas_offset(50);
        make.left.mas_equalTo(30);
    }];
    __weak typeof(self) weakSelf = self;
    [self.captchaView setTapActionWithBlock:^{
        [weakSelf requestCap];
    }];
    
    [self.sureButton setTapActionWithBlock:^{
        NSString *cap = weakSelf.capTextField.text;
        if (cap.length > 0) {
            if (weakSelf.captchaBlock) {
                weakSelf.captchaBlock(cap);
                [KLCPopup dismissAllPopups];
            }
        } else {
            [weakSelf presentMessageTips:NSLocalizedString(@"please input identifying code", nil)];
        }
    }];
}

- (void)show {
    KLCPopup *pop = [KLCPopup popupWithContentView:self showType:KLCPopupShowTypeSlideInFromTop dismissType:KLCPopupDismissTypeSlideOutToBottom maskType:KLCPopupMaskTypeDimmed dismissOnBackgroundTouch:NO dismissOnContentTouch:NO];
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyboardHide:)];
    tapGestureRecognizer.cancelsTouchesInView = NO;
    [pop addGestureRecognizer:tapGestureRecognizer];
    [pop show];
}
- (void)labelClick {
    [self requestCap];
}

- (UIImageView *)captchaView {
    if (!_captchaView) {
        _captchaView = [[UIImageView alloc] init];
        _captchaView.backgroundColor = [UIColor mainBackgroundColor];
        _captchaView.userInteractionEnabled = YES;
    }
    return _captchaView;
}

- (UITextField *)capTextField {
    if (!_capTextField) {
        _capTextField = [[UITextField alloc] init];
        _capTextField.placeholder = NSLocalizedString(@"Identifying Code", nil);
        _capTextField.delegate=self;
        _capTextField.font = [UIFont font16];
    }
    return _capTextField;
}

- (UIButton *)sureButton {
    if (!_sureButton) {
        _sureButton = [[UIButton alloc] init];
        [_sureButton setTitle:NSLocalizedString(@"Confirm", nil) forState:UIControlStateNormal];
        [_sureButton setBackgroundColor:[UIColor c1Color]];
        _sureButton.layer.cornerRadius = 20.f;
        _sureButton.layer.masksToBounds = YES;
    }
    return _sureButton;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [_capTextField resignFirstResponder];
    return YES;
}
-(void)keyboardHide:(UITapGestureRecognizer*)tap{
    [self endEditing:YES];
}
/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */

@end
